$(function () {
    var orders = [];
    var dataItems = {};
    var blankData = {
        id: 0,
        serialNumber: '',
        certificateNumber: '',
        companyName: '',
        ownerName: '',
        idNumber: '',
        phoneNumber: '',
        address: '',
        deliveryDate: null,
        registrationDate: null,
        vehicleNumber: '',
        vehicleType: '',
        vehicleNature: '',
        vehicleBrand: '',
        vehicleModel: '',
        vin: '',
        weight: null,
        powerType: '',
        engineNumber: '',
        batteryNumber: '',
        operator: '',
        processingDate: null,
        remark: '',
        cancellationDate: null,
        vehicleManagementOffice: '',
        recoveredMaterials: '',
        unrevokedMaterials: '',
        checkCode: null,
        deleted: false
    };

    setupDataModal();
    getDataList();

    $('#submit-button').click(function () {
        $('#search-form [name="pageNumber"]').val(0);
        getDataList();
    });

    $('#add-button').click(function () {
        var data = JSON.parse(JSON.stringify(blankData));
        var realName = $('.main-content').data('real-name');
        var companyName = $('.main-content').data('company-name');
        if (realName) data.operator = realName;
        if (companyName) data.companyName = companyName;
        if ('remark' in dataItems && dataItems.remark && dataItems.remark.length > 0) {
            data.remark = dataItems.remark[0];
        }
        showDataModal(data);
    });

    $('#pagination-bar').on('pageChange', function (e, page) {
        $('#search-form [name="pageNumber"]').val(page - 1);
        getDataList();
    });

    $('#data-list-group table tbody').on('click', 'tr', function () {
        var data = null;
        var id = $(this).data('id') + '';
        for (var i = 0, count = orders.length; i < count; i++) {
            if (orders[i].id + '' === id) {
                data = orders[i];
                break;
            }
        }
        if (!data) {
            window.showInformationAlert(1, '订单信息获取失败。');
        } else {
            showDataModal(data);
        }
    });

    $('#data-modal .save-button').click(function () {
        var $saveButton = $(this);
        if ($saveButton.hasClass('loading')) return;

        var requestData = readDataFormData();
        window.loadingButton($saveButton, true);
        window.setModalClosable($('#data-modal'), false);
        $('#data-modal .modal-body .alert').alert('close');
        $.post('/api/order/' + requestData.id, requestData, function (data) {
            window.loadingButton($saveButton, false);
            window.setModalClosable($('#data-modal'), true);
            if (data.code === 200) {
                $('#data-modal').one('hidden.bs.modal', function () {
                    getDataList();
                });
                $('#data-modal').modal('hide');
            } else {
                var $alert = window.createAlert('alert-danger', data.message);
                $('#data-modal .modal-body').append($alert);
            }
        });
    });

    $('#data-modal .delete-button').click(function () {
        if ($('#data-modal .save-button').hasClass('loading')) return;

        $('#data-modal').one('hidden.bs.modal', function () {
            var id = $('#data-form input[name="id"]').val();
            var message = '确定要删除当前订单吗？';
            window.showQuestionAlert(2, message, '', '', function () {
                window.showLoadingBox('正在删除订单...');
                $.ajax({
                    url: '/api/order/' + id,
                    type: 'DELETE',
                    success: function (data) {
                        window.hideLoadingBox(function () {
                            if (data.code === 200) {
                                getDataList();
                            } else {
                                window.showInformationAlert(3, data.message);
                            }
                        });
                    }
                });
            });
        });
        $('#data-modal').modal('hide');
    });

    $('#print-modal .ok-button').click(function () {
        var id = $(this).data('id');
        var index = $('#print-modal .index-input').val();
        var shading = $('#shading-input').prop('checked') ? 1 : 0;
        var url = '/page/pdf/recyclingCertificate/' + id + '/' + index + '/' + shading;
        $('#print-modal').one('hidden.bs.modal', function () {
            openLink(url);
        });
        $('#print-modal').modal('hide');
    });

    $('#print-modal2 .ok-button').click(function () {
        var id = $(this).data('id');
        var index = $('#print-modal2 .index-input').val();
        var url = '/page/pdf/cancellationCertificate/' + id;
        if (parseInt(index) === 1) {
            url = '/page/pdf/cancellationCertificate2/' + id;
        }
        $('#print-modal2').one('hidden.bs.modal', function () {
            openLink(url);
        });
        $('#print-modal2').modal('hide');
    });

    $('.link-input-group .input-group-append .btn').click(function () {
        var url = $(this).closest('.link-input-group').find('.form-control').val();
        if (url) openLink(url);
    });

    $('#data-modal .print-dropdown .dropdown-menu').on('click', '.dropdown-item', function () {
        var id = $('#data-form input[name="id"]').val();
        var index = $(this).index();
        $('#data-modal').one('hidden.bs.modal', function () {
            showPrintModal(id, index);
        });
        $('#data-modal').modal('hide');
    });

    function getDataList() {
        var requestData = window.readFormData($('#search-form'), true);
        window.showLoadingBox('数据加载中...');
        $.get('/api/orders', requestData, function (data) {
            window.hideLoadingBox(function () {
                if (data.code === 200) {
                    orders = data.data.list;
                    dataItems = data.data.extraData;
                    refreshDualInputGroups();
                } else {
                    orders = [];
                    dataItems = {};
                }
                window.showTableData(data, getDataList);
            });
        });
    }

    function showDataModal(data) {
        showDataFromData(data);
        window.loadingButton($('#data-modal .save-button'), false);
        window.setModalClosable($('#data-modal'), true);
        $('#data-modal .modal-body .alert').alert('close');
        if (parseInt(data.id) === 0) {
            $('#data-modal .modal-footer .delete-button').addClass('d-none');
            $('#data-modal .modal-footer .print-button').addClass('d-none');
        } else if (data.checkCode) {
            $('#data-modal .modal-footer .delete-button').addClass('d-none');
            $('#data-modal .modal-footer .print-button').removeClass('d-none');
        } else if (data.deleted) {
            $('#data-modal .modal-footer .delete-button').addClass('d-none');
            $('#data-modal .modal-footer .print-button').addClass('d-none');
        } else {
            $('#data-modal .modal-footer .delete-button').removeClass('d-none');
            $('#data-modal .modal-footer .print-button').addClass('d-none');
        }
        $('#data-modal').modal({backdrop: 'static', keyboard: false});
    }

    function showPrintModal(id, index) {
        var $modal = index === 1 ? $('#print-modal2') : $('#print-modal');
        if (!$modal.find('.index-input').selectpicker) {
            window.selectPicker($modal.find('.index-input'), false);
        }
        $modal.find('.ok-button').data('id', id);
        $modal.modal({backdrop: 'static', keyboard: false});
        $modal.one('hidden.bs.modal', function () {
            $('#data-modal').modal({backdrop: 'static', keyboard: false});
        });
    }

    function showDataFromData(data) {
        window.showFormData($('#data-form'), data);
        $.each($('#data-form .dual-input-group .input-group-content select'), function (index, element) {
            var $select = $(element);
            var $checkbox = $select.closest('.dual-input-group').find('.input-group-prepend input');
            var name = $select.prop('name');
            var value = $.trim(name in data ? data[name] : '');
            $select.selectpicker('val', value);
            if ($checkbox.prop('checked')) {
                $checkbox.trigger('click');
            }
        });
        $.each($('#data-form .date-picker'), function (index, element) {
            var $datePicker = $(element);
            var $input = $datePicker.find('input');
            var value = $input.val();
            if ($.trim(value).length === 0) value = null;
            $datePicker.datetimepicker('date', value);
        });
        if (data.checkUrl) {
            $('#check-url-row').find('.form-control').val(data.checkUrl);
            $('#check-url-row').removeClass('d-none');
        } else {
            $('#check-url-row').addClass('d-none');
        }
        if (data.checkCode) {
            $('#active-input').prop('checked', true);
        } else {
            $('#active-input').prop('checked', false);
        }
        if (data.deleted) {
            $('#deleted-input').prop('checked', true);
        } else {
            $('#deleted-input').prop('checked', false);
        }
    }

    function readDataFormData() {
        var data = window.readFormData($('#data-form'), true);
        data.generateCheckCode = $('#active-input').prop('checked');
        data.deleted = $('#deleted-input').prop('checked');
        $.each($('#data-form .dual-input-group .input-group-content select'), function (index, element) {
            var $select = $(element);
            var $input = $select.closest('.dual-input-group').find('input.data-item');
            var $checkbox = $select.closest('.dual-input-group').find('.input-group-prepend input');
            var name = $select.prop('name');
            var value = '';
            if ($checkbox.prop('checked')) {
                value = $select.val();
            } else {
                value = $input.val();
            }
            data[name] = $.trim(value);
        });
        return data;
    }

    function setupDataModal() {
        $.each($('#data-form .dual-input-group .input-group-content select'), function (index, element) {
            var $select = $(element);
            var $checkbox = $select.closest('.dual-input-group').find('.input-group-prepend input');
            var html = template('item-template', {list: []});
            $select.html(html);
            window.selectPicker($select, true);
            $select.closest('.input-group-content').find('.bootstrap-select').addClass('d-none');
            $checkbox.on('change', function () {
                var $group = $(this).closest('.dual-input-group');
                var checked = $(this).prop('checked');
                if (checked) {
                    $group.find('.input-group-content > input.form-control').addClass('d-none');
                    $group.find('.input-group-content .bootstrap-select').removeClass('d-none');
                    window.setFocusTo($group.find('.input-group-content .bootstrap-select > .btn'), 100);
                } else {
                    $group.find('.input-group-content > input.form-control').removeClass('d-none');
                    $group.find('.input-group-content .bootstrap-select').addClass('d-none');
                    window.setFocusTo($group.find('.input-group-content input.form-control'), 100);
                }
            });
        });
        window.datetimePicker($('#data-form .date-picker'));
    }

    function refreshDualInputGroups() {
        $.each($('.dual-input-group .input-group-content select'), function (index, element) {
            var $select = $(element);
            var name = $select.prop('name');
            var itemList = name in dataItems ? dataItems[name] : [];
            var html = template('item-template', {list: itemList});
            $select.html(html);
            $select.selectpicker('refresh');
        });
    }

    function openLink(url) {
        var $a = $('<a target="_blank" style="visibility:hidden">temp</a>');
        $a.prop('href', url);
        $('body').append($a);
        $a[0].click();
        $a.remove();
    }
});
